<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019-3-25
 * Time: 16:10
 */
namespace frontend\wx;

use common\models\Userr;

define("TOKEN", "Alps");
class wxapi
{
    public function valid()
    {
        $nonce     = $_GET['nonce'];
        $token     = 'Alps';
        $timestamp = $_GET['timestamp'];
        $echostr   = $_GET['echostr'];
        $signature = $_GET['signature'];
        //形成数组，然后按字典序排序
        $array = array();
        $array = array($nonce, $timestamp, $token);
        sort($array);
        //拼接成字符串,sha1加密 ，然后与signature进行校验
        $str = sha1( implode( $array ) );
        if( $str  == $signature && $echostr ){
            //第一次接入weixin api接口的时候
            echo  $echostr;
            exit;
        }else{
            $this->getMenu();
            $this->reponseMsg();

        }

        //valid signature , option

    }

    public function getToken(){
        $appid = "wx7646ca6bb92fa339";
        $appsecret = "2584e088977867de01b1015def0ea45d";
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        $jsoninfo = json_decode($output, true);
        $access_token = $jsoninfo["access_token"];
        return $access_token;
    }
    public function getMenu()
    {
        $token = $this->getToken();

        $MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" . $token;

        $ch = curl_init();
        $jsonmenu = '{
	"button": [

		{
			"type": "view",
			"name": "入口",
			"url": "http://xiaochaoyang.cn/Blog/frontend/web/index.php?r=post%2Findex"
		},

		{
			"name": "最新文章",
			"sub_button": [{
					"type": "view",
					"name": "最新文章",
					"url": "http://m.hao123.com/a/tianqi"
				},
				{
					"type": "click",
					"name": "点击获取最新文章",
					"key": "V1001_TODAY_MUSIC"
				}
			]
		},
		{
			"name": "合作与留言",
			"sub_button": [{
				"type": "view",
				"name": "合作",
				"url": "http://m.hao123.com/a/tianqi"
			}, {
				"type": "view",
				"name": "留言",
				"url": "http://m.hao123.com/a/tianqi"
			}]
		}
	]
}';
        curl_setopt($ch, CURLOPT_URL, $MENU_URL);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonmenu);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $info = curl_exec($ch);

        if (curl_errno($ch)) {
            echo 'Errno' . curl_error($ch);
        }

        curl_close($ch);

    }
    public function responseMsg()
    {
        //get post data, May be due to the different environments
        $postStr = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : file_get_contents("php://input");;

        //extract post data
        if (!empty($postStr)) {
            /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
               the best way is to check the validity of xml by yourself */
            libxml_disable_entity_loader(true);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $fromUsername = $postObj->FromUserName;
            $toUsername = $postObj->ToUserName;
            $keyword = trim($postObj->Content);
            $time = time();
            $textTpl = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Content><![CDATA[%s]]></Content>
							<FuncFlag>0</FuncFlag>
							</xml>";
            if (!empty($keyword)) {
                $msgType = "text";
                $contentStr = "Welcome to wechat world!";
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                echo $resultStr;
            } else {
                echo "Input something...";
            }

        } else {
            echo "";
            exit;
        }
    }
}